﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using App.MVC.Extend;
using App.MVC.Mediators;
using App.MVC.Models.Log;
using App.MVC.Models.ValueObjects;
using App.MVC.Toolikits;
using ArxOne.MrAdvice.Advice;

namespace App.MVC.Attributes
{
    [Serializable]
    [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
    public class ExceptionAspect : Attribute, IMethodAdvice
    {
        /// <summary>
        /// 异常日志字段
        /// </summary>
        protected readonly ExceptionLog _exceptionLog;

        /// <summary>
        /// 异常消息
        /// </summary>
        protected ExceptionMessage _exceptionMessage;
        protected ExceptionAspect()
        {
            this._exceptionLog = new ExceptionLog();
        }
        public void Advise(MethodAdviceContext context)
        {
            try
            {
                context.Proceed();
            }
            catch (Exception exception)
            {
                this.OnException(context, exception);
            }
        }
        /// <summary>
        /// 发生异常事件
        /// </summary>
        /// <param name="context">方法元数据</param>
        /// <param name="exception">异常实例</param>
        protected virtual void OnException(MethodAdviceContext context, Exception exception)
        {

            //初始化异常日志
            this._exceptionLog.BuildBasicInfo(context);
            this._exceptionLog.BuildMethodArgsInfo(context);
            this._exceptionLog.BuildExceptionInfo(exception);
            //插入数据库
            LogHelper.WriteLog_Sql(exception);
            ////无需事务
            //using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
            //{
            //    //插入数据库
            //    Guid newId = LogMediator.Write(this._exceptionLog);

            //    scope.Complete();

            //    //初始化异常消息
            //    this._exceptionMessage = new ExceptionMessage(exception.Message, newId);

            //}
        }
    }
}